package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.strategy.ProcessPaidRecord;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <a href="https://www.shallowrecall.top/">Recall`Blog</a></br>
 * <a href="https://github.com/ShallowRecall">GitHub</a>
 *
 * @author Recall
 * @createTime 2025/06/12 00:50
 **/
@Service("1001")
@Slf4j
public class AlbumTypePaidRecord implements ProcessPaidRecord {

    @Autowired
    private UserPaidAlbumMapper userPaidAlbumMapper;

    @Override
    public void processDiffItemTypePaidRecord(UserPaidRecordVo userPaidRecordVo) {

        String orderNo = userPaidRecordVo.getOrderNo();
        Long userId = userPaidRecordVo.getUserId();
        List<Long> itemIdList = userPaidRecordVo.getItemIdList();

        // 1.幂等性校验（检查该订单是否已经在流水表中 如果在 不用保存 反之才保存）
        LambdaQueryWrapper<UserPaidAlbum> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserPaidAlbum::getOrderNo, orderNo);
        wrapper.eq(UserPaidAlbum::getUserId, userId);
        UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(wrapper);
        if (userPaidAlbum != null) {
            log.error("该专辑类型的流水已经记录过");
            return;
        }
        // 2.保存流水
        userPaidAlbum = new UserPaidAlbum();
        userPaidAlbum.setOrderNo(orderNo);
        userPaidAlbum.setUserId(userId);
        userPaidAlbum.setAlbumId(itemIdList.get(0));  // 专辑id
        int insert = userPaidAlbumMapper.insert(userPaidAlbum);
        log.info("记录专辑流水：{}", insert > 0 ? "success" : "fail");

    }
}
